<template>
  <Layout>
    <div class="personal-center">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        当前位置：<router-link to="/home" class="breadcrumb-link">首页</router-link> > <span class="breadcrumb-current">个人中心</span>
      </div>

      <div class="content-wrapper">
        <!-- 左侧个人信息卡片 -->
        <div class="info-card">
          <div class="avatar-section">
            <img :src="userInfo.avatar || '/default-avatar.png'" alt="用户头像" class="avatar">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:9090/api/upload/image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <el-button size="small">更换头像</el-button>
            </el-upload>
          </div>
          <div class="user-info">
            <h3>{{ userInfo.name }}</h3>
            <p>志愿者编号：{{ userInfo.volunteerId }}</p>
            <p>累计服务时长：{{ userInfo.totalServiceHours }}小时</p>
            <p>系统等级：{{ userInfo.systemRank }}</p>
          </div>
        </div>

        <!-- 右侧主要内容区 -->
        <div class="main-content">
          <el-tabs v-model="activeTab">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form :model="userInfo" label-width="100px">
                <el-form-item label="姓名">
                  <el-input v-model="userInfo.name" class="bordered-input"/>
                </el-form-item>
                <el-form-item label="政治面貌">
                  <el-select v-model="userInfo.politicalAffiliation" class="bordered-input">
                    <el-option label="中共党员" :value="1" />
                    <el-option label="预备党员" :value="2" />
                    <el-option label="共青团员" :value="3" />
                    <el-option label="群众" :value="4" />
                  </el-select>
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="userInfo.phoneNumber" class="bordered-input"/>
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="userInfo.email" class="bordered-input"/>
                </el-form-item>
                <el-form-item label="微信">
                  <el-input v-model="userInfo.wechat" class="bordered-input"/>
                </el-form-item>
                <el-form-item label="QQ">
                  <el-input v-model="userInfo.qq" class="bordered-input"/>
                </el-form-item>
                <el-form-item label="地址">
                  <el-input v-model="userInfo.address" class="bordered-input"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveUserInfo">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 我的项目 -->
            <el-tab-pane label="我的项目" name="projects">
              <el-table :data="myProjects" style="width: 100%">
                <el-table-column prop="activityName" label="项目名称" />
                <el-table-column prop="registrationTime" label="参与时间" :formatter="formatTime" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    {{ scope.row.status  }}
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 我的队伍 -->
            <el-tab-pane label="我的队伍" name="teams">
              <el-table :data="myTeams" style="width: 100%">
                <el-table-column prop="organizationName" label="队伍名称" />
                <el-table-column prop="establishmentDate" label="成立时间" :formatter="formatDate"/>
                <el-table-column prop="address" label="所属区域" />
                <el-table-column label="评分" width="200">
                  <template #default="scope">
                    <el-rate 
                      v-model="scope.row.rating" 
                      :max="5"
                      @change="(value) => handleRatingChange(value, scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button size="small" @click="quitTeam(scope.row)">退出队伍</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Layout from '@/components/Layout.vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from "dayjs";
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref('basic')

// 用户信息
const userInfo = ref({
  avatar: '',
  name: '',
  volunteerId: '',
  totalServiceHours: 0,
  systemRank: 0,
  politicalAffiliation: 1,
  phoneNumber: '',
  email: '',
  wechat: '',
  qq: '',
  address: ''
})

// 我的项目列表
const myProjects = ref([])

// 我的队伍列表
const myTeams = ref([])

const formatTime = (row) => {
  return row.registrationTime ? dayjs(row.registrationTime).format("YYYY-MM-DD HH:mm:ss") : "";
};

const formatDate = (row) => {
  return row.establishmentDate ? dayjs(row.establishmentDate).format("YYYY-MM-DD") : "";
};

// 处理评分变化
const handleRatingChange = async (value, team) => {
  try {
    const volunteerId = localStorage.getItem('volunteerId')
    const evaluation = {
      volunteerId: volunteerId,
      organizationId: team.organizationId,
      score: value,
      evaluationDate: new Date()
    }
    
    // 先查询是否已有评分
    const scoreResponse = await axios.get(`http://localhost:9090/evaluation/scores/${team.organizationId}/${volunteerId}`)
    
    let response
    if (scoreResponse.data) {
      // 已有评分,走修改接口
      response = await axios.put('http://localhost:9090/evaluation/update', evaluation)
    } else {
      // 没有评分,走新增接口
      response = await axios.post('http://localhost:9090/evaluation/add', evaluation)
    }
    
    if (response.data) {
      ElMessage.success('评分成功')
    } else {
      ElMessage.error('评分失败')
    }
  } catch (error) {
    ElMessage.error('评分失败')
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 从缓存获取volunteerId
    const volunteerId = localStorage.getItem('volunteerId')
    // if (!volunteerId) {
    //   ElMessage.error('未找到志愿者ID')
    //   return
    // }else if (localStorage.getItem('type') !== '') {
    //   ElMessage.error('请先登录')
    //   router.push('/login')
    //   return
    // }
    console.log('这个是个人中心的type:'+localStorage.getItem('type'))

    if (localStorage.getItem('type') === ''){
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }else if (localStorage.getItem('type') === 'admin'){
      ElMessage.error('当前账号不是志愿者账号，请使用志愿者账号登录')
      return
    }else if (!volunteerId){
      ElMessage.error('未找到志愿者ID')
      return
    }

    // 调用后端接口获取志愿者信息
    const response = await axios.get(`http://localhost:9090/volunteers/${volunteerId}`)
    if (response.status === 200) {
      const volunteerData = response.data.data
      userInfo.value = {
        avatar: volunteerData.avatar,
        name: volunteerData.name,
        volunteerId: volunteerData.volunteerId,
        totalServiceHours: volunteerData.totalServiceHours,
        systemRank: volunteerData.systemRank,
        politicalAffiliation: volunteerData.politicalAffiliation,
        phoneNumber: volunteerData.phoneNumber,
        email: volunteerData.email,
        wechat: volunteerData.wechat,
        qq: volunteerData.qq,
        address: volunteerData.address
      }

      // 获取我的项目列表
      const projectResponse = await axios.get(`http://localhost:9090/registrations/checkByVolunteerId?volunteerId=${volunteerId}`)
      if (projectResponse.status === 200) {
        myProjects.value = projectResponse.data || []
      }

      // 获取我的队伍列表
      const teamsResponse = await axios.get(`http://localhost:9090/organizations/searchByVolunteerId?volunteerId=${volunteerId}`)
      if (teamsResponse.status === 200) {
        myTeams.value = teamsResponse.data || []
        
        // 获取每个队伍的评分
        for (let team of myTeams.value) {
          try {
            const scoreResponse = await axios.get(`http://localhost:9090/evaluation/scores/${team.organizationId}/${volunteerId}`)
            team.rating = scoreResponse.data ? Number(scoreResponse.data) : 0
          } catch (error) {
            team.rating = 0
          }
        }
      }

    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  try {
    const response = await axios.put(`http://localhost:9090/volunteers/updateSelective`, {
      volunteerId: userInfo.value.volunteerId,
      name: userInfo.value.name,
      avatar: userInfo.value.avatar,
      politicalAffiliation: userInfo.value.politicalAffiliation,
      phoneNumber: userInfo.value.phoneNumber,
      email: userInfo.value.email,
      wechat: userInfo.value.wechat,
      qq: userInfo.value.qq,
      address: userInfo.value.address
    })
    
    if(response.status === 200) {
      ElMessage.success('保存成功')
      await fetchUserInfo() // 重新加载用户信息
    } else {
      ElMessage.error('保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 头像上传成功处理
const handleAvatarSuccess = async (response) => {
  if(response) {
    try {
      const updateResponse = await axios.put(`http://localhost:9090/volunteers/updateSelective`, {
        volunteerId: userInfo.value.volunteerId,
        avatar:"http://localhost:9090/api/upload/uploads/"+response
      })
      
      if(updateResponse.status === 200) {
        ElMessage.success('头像更新成功')
        await fetchUserInfo() // 重新加载用户信息
      } else {
        ElMessage.error('头像更新失败')
      }
    } catch(error) {
      ElMessage.error('头像更新失败')
    }
  } else {
    ElMessage.error('头像上传失败')
  }
}

// 查看项目详情
const viewProjectDetail = (project) => {
  // 实现查看项目详情的逻辑
}

// 退出队伍
const quitTeam = async (team) => {
  try {
    const volunteerId = localStorage.getItem('volunteerId')
    const response = await axios.put(`http://localhost:9090/volunteers/leaveTeam`, {
      volunteerId: volunteerId,
      organizationIds: team.organizationId.toString()
    })
    
    if(response.data.success) {
      ElMessage.success('退出队伍成功')
      await fetchUserInfo() // 重新加载数据
    } else {
      ElMessage.error(response.data.message || '退出队伍失败')
    }
  } catch (error) {
    ElMessage.error('退出队伍失败')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.personal-center {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.breadcrumb-link {
  color: #dd2b2b;
  text-decoration: none;
}

.breadcrumb-link:hover {
  color: #66b1ff;
}

.breadcrumb-current {
  color: #dd2b2b;
}

.content-wrapper {
  display: flex;
  gap: 20px;
}

.info-card {
  width: 300px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.user-info {
  text-align: center;
}

.user-info h3 {
  margin-bottom: 10px;
}

.user-info p {
  margin: 5px 0;
  color: #666;
}

.main-content {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-form {
  max-width: 500px;
}

.bordered-input {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.bordered-input:hover {
  border-color: #c0c4cc;
}

.bordered-input:focus {
  border-color: #409EFF;
}
</style>